<script setup>

import { ref, reactive, onMounted, nextTick } from 'vue'
import { getTownsAndProjectCount } from '@/api/home'
import { areaPositionIndex } from '@/utils/index'
import * as echarts from "echarts"
import zhouchengJson from '../../../assets/zhoucheng.json'

const props = defineProps({
    projectArea: {
        type: Array,
        default: []
    },
    projectTotalCount: {
        type: Number,
        default: 0
    }
})


let eCharts = null
let map = ref(null)

// 有项目的镇列表
let townsData = ref([])

onMounted(() => {
    init(props.projectArea, props.projectTotalCount)

    // eCharts = echarts.init(map.value)

    // echarts.registerMap('city', {geoJSON:data});
    // eCharts.setOption(option)

    // eCharts.on('click', function (params) {
    //     // 在用户点击后控制台打印数据的名称
    //     console.log(params.data);
    // });
})

const init = async (data = [], projectTotalCount = 0) => {
    townsData = data && data.length ? areaSetMark(data, projectTotalCount) : await getZcProject()

    echarts.registerMap("city", { geoJSON: zhouchengJson })
    eCharts = echarts.init(map.value)
    eCharts.setOption(option())
    window.addEventListener("resize", () => {
        if (!eCharts) return;
        eCharts.resize();
    })
}

const option = () => {
    return reactive({
        tooltip: {
            trigger: 'item',
            showDelay: 0,
            transitionDuration: 0.2
        },
        geo: [
            {
                map: 'city',
                itemStyle: {
                    normal: {
                        areaColor: '#12C0E9',
                        borderColor: '#12C0E9',
                    }
                }
            },
            {
                map: 'city',
                top: '8%',
                itemStyle: {
                    // areaColor: '#004E8F',
                    // borderColor: '#5EBFE4',
                    // borderWidth: 1,
                    // boxShadow: '0px 0px 25px 0px #3271E6;',
                    normal: {//阴影
                        areaColor: '#0B54CD',
                        shadowColor: '#12C0E9',
                        borderColor: '#12C0E9',
                        borderWidth: 1,
                        shadowOffsetX: 0,
                        shadowOffsetY: 2
                    },
                },
                label: {
                    show: true,
                    color: '#fff'
                },
                emphasis: {
                    label: {
                        show: true,
                        color: '#fff'
                    },
                    itemStyle: {
                        areaColor: '#00B4B4',
                    }
                },
            }
        ],
        series: [
            { // 涟漪效果
                // name: 'Top 6',
                type: 'effectScatter',
                coordinateSystem: 'geo',
                data: townsData,
                symbolSize: function (val) {
                    return 12;
                },
                encode: {
                    value: 10
                },
                showEffectOn: 'render',
                rippleEffect: {
                    brushType: 'stroke',
                    color: '#BCFFFB'
                },
                emphasis: {
                    scale: false
                },
                label: {
                    formatter: '{b}',
                    position: 'right',
                    show: false
                },
                itemStyle: {
                    shadowBlur: 10,
                    shadowColor: 'rgba(230, 10, 10, 1)',
                    color: '#BCFFFB'
                },
                zlevel: 1,
                tooltip: {
                    trigger: "item",
                    backgroundColor: "rgba(0, 0, 0, 0.4)",

                    show: true,
                    formatter: function(params) {
                        let count = params && params.value ? params.value[2] : 0
                        return params.name + '<br/>项目数:' + count + '个';
                    },
                    textStyle: {
                        color: "#01FFF6" //设置文字颜色
                    },
                }
            }
        ]
    })
}

// 获取皱城区区域和项目数量
const getZcProject = () => {
    return new Promise((resolve) => {
        
        getTownsAndProjectCount().then(res => {
            if(res.success){
                let { townsList, projectCount } = res.result
                resolve(areaSetMark(townsList, projectCount))
            }  
        })
    })
}

// 有项目的区域加标记
const areaSetMark = (townsList, projectCount) => {
    let towns = []
    for(let i = 0;i < townsList.length; i++){
        let { counts, townsName } = townsList[i]
        if(counts){
            towns.push({
                name:townsName,
                value: [...mapGetCenter(zhouchengJson.features[areaPositionIndex[townsName]].geometry.coordinates[0]), counts]
            })
        }
    }
    jumpNumber(0, projectCount, 10)
    return towns
}





// 获取区域中间点
const mapGetCenter = (pointArray) => {
    var sortedLongitudeArray = pointArray.map(item => item[1]).sort();//首先对经度进行排序，红色部分是array中经度的名称
    var sortedLatitudeArray = pointArray.map(item => item[0]).sort();//对纬度进行排序，红色部分是array中纬度的名称
    var centerLongitude = ((parseFloat(sortedLongitudeArray[0]) + parseFloat(sortedLongitudeArray[sortedLongitudeArray.length - 1])) / 2).toFixed(4);
    const centerLatitude = ((parseFloat(sortedLatitudeArray[0]) + parseFloat(sortedLatitudeArray[sortedLatitudeArray.length - 1])) / 2).toFixed(4);

    //如果经纬度在array中不是数字类型，需要转化为数字类型进行计算，如果是可以去掉parseFloat处理
    //console.log(centerLongitude+"kkk"+centerLatitude);
    return [centerLatitude, centerLongitude];
}

let projectTotal = $ref(0)
let diffTimer = $ref(undefined)

/**
 * start:起始数据
 * end:最终数据
 * time:动画时间
* */
const jumpNumber = (start, end, time) => {
    projectTotal = start
    let endNum = end
    let lastNum = ''  //小数
    let digit = 0 //小数位数
    let step = 0  //累加步长
    const len = parseInt(end).toString().length
    //判断是小数
    if (parseInt(end) !== end) {
        endNum = parseInt(end)
        lastNum = end.toString().split('.')[1]
        digit = lastNum.length
    }
    const timer = setInterval(() => {
        if (projectTotal < (endNum - step)) {
            step++
            //数据过大，后面几位数随机跳动
            if (len >= 6) {
                let bigNumber = getRandomNum(len - 3)
                const leng = parseInt(start).toString().length
                const length = leng - bigNumber.length
                //截取岁随机数前面的数
                const cur = length <= 0 ? parseInt(start) : parseInt(start.toString().slice(0, length))
                start = cur + step + bigNumber
            } else {
                start = parseInt(start) + step
            }
            projectTotal = parseFloat(start)
        } else {
            clearInterval(timer)
            projectTotal = end
        }
    }, time)
}



</script>

<template>
    <div class="map-warp">
        <div class="title color-highlight font-b"></div>

        <div class="project-count flex-center">
            <span>总项目</span>

            <span class="count-item" v-for="(n, index) in String(projectTotal)" :key="index">{{ n }}</span>

            <span>个</span>
        </div>

        <div class="map" ref="map">

        </div>

    </div>
</template>

<style lang="less" scoped>
.map-warp {
    width: 816px;
    height: 534px;
    background: url('../../../assets/images/center-map-bg.png') center no-repeat;
    background-size: 100% 100%, 568px 90px;
    position: relative;

    .title {
        text-align: center;
        width: 100%;
        height: 84px;
        background: url('../../../assets/images/center-map-top-bg.png') center no-repeat;
        position: absolute;
        top: -15px;
        z-index: 9;
    }

    .project-count {
        padding: 70px 0 20px;
        font-size: 24px;
        color: #fff;

        .count-item {
            display: inline-block;
            width: 36px;
            height: 48px;
            line-height: 48px;
            background: linear-gradient(0deg, #07256A, rgba(7, 37, 106, 0));
            border: 1px solid;
            // box-shadow: linear-gradient(0deg, rgba(0,180,255,0.8000), rgba(0,180,255,0.8000)) 1 1;
            border-image: linear-gradient(0deg, rgba(0, 180, 255, 0.8000), rgba(0, 180, 255, 0.8000)) 1 1;
            border-radius: 3px;
            text-align: center;
            margin: 0 5px;
            font-family: DigifaceWide-Regular;
            color: var(--color-highlight);
            font-size: 41px;
            box-shadow: 0 2px 10px 3px #1C4EB0 inset;
        }
    }

    .map {
        width: 100%;
        height: 480px;
        margin-top: -60px
    }
}
</style>